package qingyu.ai.common.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

/**
 * Activity管理类
 */
public class ActManager {
    private static Stack<Activity> activityStack;
    private static ActManager instance;

    private ActManager() {
        if (instance != null)
            throw new RuntimeException("you not create ActManager instance");
    }


    public static ActManager getAppManager() {
        if (instance == null) {
            synchronized (ActManager.class) {
                if (instance == null) {
                    instance = new ActManager();
                    activityStack = new Stack<>();
                }
            }
        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     *
     * @param activity
     * @return
     */
    public boolean addActivity(Activity activity) {
        return activity != null ? activityStack.add(activity) : false;
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入，位于栈顶）
     *
     * @return Activity
     */
    public Activity currentActivity() {
        return activityStack.size() > 0 ? activityStack.lastElement() : null;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入，位于栈顶）
     *
     * @return
     */
    public boolean finishAct() {
        return finishAct(activityStack.lastElement());
    }

    /**
     * 结束指定的Activity
     *
     * @param activity 指定Activity 对象
     * @return
     */
    public boolean finishAct(Activity activity) {
        if (activity != null) {
            boolean remove = activityStack.remove(activity);
            if (remove)
                activity.finish();
            return remove;
        }
        return false;
    }

    /**
     * 结束指定类名的Activity
     *
     * @param cls 指定的Activity class
     */
    public void finishAct4Class(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishAct(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = activityStack.size(); i > 0; i--) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     *
     * @param context
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
